/*
 * @Author: zy
 * @Date: 2022-07-26 16:27:53
 * @LastEditTime: 2022-07-26 17:59:08
 * @Description: 文件上传
 */
export  const  uploadFile = params => {
  //默认地址七牛
  let url = "https://upload-z2.qiniup.com";
  if (params.region) {
    url = `https://upload-${params.region}.qiniup.com`;
  } else if (params.uploadUrl) {
    url = params.uploadUrl;
  }
  let { filePath, formData, uploadUrl = url, processHandler } = params;
  return new Promise((resolve, reject) => {
    let uploadTask = uni.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: "file",
      formData: formData,
      success(res) {
        if (typeof res.data === "string") {
          try {
            res.data = JSON.parse(res.data);
          } catch (e) {
            // 转换失败
            console.log("转换失败");
            reject(new Error("upload error"));
          }
          if (res.data.key) {
            resolve(res.data);
          } else {
            reject(new Error("upload error"));
          }
        }
      },
      fail(err) {
        console.log("upload error", err);
        reject(new Error("upload error"));
      }
    });
    uploadTask.onProgressUpdate(res => {
      if (processHandler) {
        processHandler(res.progress);
      }
    });
  });
};

export default uploadFile;